package com.hzz.service.user;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzz.api.user.IOrgInfoService;
import com.hzz.dao.user.IOrgInfoDao;
import com.hzz.dto.user.OrgInfoDto;
import com.hzz.entity.user.OrgInfo;
import com.hzz.framework.NodeTree;
import com.hzz.framework.Response;
import com.hzz.framework.SysErrorCode;
import com.hzz.framework.annotation.FeignService;
import com.hzz.framework.exception.ServiceException;
import com.hzz.framework.service.BaseService;
import com.hzz.framework.util.CommonConstant;
import com.hzz.framework.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@FeignService
@Slf4j
public class OrgInfoService extends BaseService implements IOrgInfoService {
    @Autowired
    IOrgInfoDao orgInfoDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = CommonConstant.DB_DEFAULT_TIMEOUT, rollbackFor = {Exception.class, RuntimeException.class})
    public Response saveOrUpdateData(OrgInfoDto dto) throws Exception {
        Response result = new Response(0,"success");
        try {
            OrgInfo entity = copyTo(dto, OrgInfo.class);
            //判断数据是否存在
            if (orgInfoDao.isDataExist(entity) != 0) {
                //数据存在
                orgInfoDao.update(entity);
            } else {
                //新增
                if(entity.getId()==null){
                    entity.setId(IdUtil.nextId());
                }
                orgInfoDao.insert(entity);
                result.data=entity.getId();
            }
        } catch (Exception e) {
            log.error("信息保存异常!", e);
            throw new ServiceException(SysErrorCode.defaultError,e.getMessage());
        }
        return result;
    }

    @Override
    public String deleteData(OrgInfoDto dto) throws Exception {
        String result = "success";
        try {
            OrgInfo entity = copyTo(dto, OrgInfo.class);
            if(orgInfoDao.deleteByPrimaryKey(entity)==0){
                throw new RuntimeException("数据不存在!");
            }
        } catch (Exception e) {
            log.error("物理删除异常!", e);
            throw new ServiceException(SysErrorCode.defaultError,e.getMessage());
        }
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = CommonConstant.DB_DEFAULT_TIMEOUT, rollbackFor = {Exception.class, RuntimeException.class})
    public String deleteDataById(OrgInfoDto dto) throws Exception {
        String result = "success";
        try {
            OrgInfo entity = copyTo(dto, OrgInfo.class);
            if(CommonConstant.HZB_ORG_ID.equals(entity.getId())){
                throw new RuntimeException("无法删除,原因:系统内置河长办");
            }
            //查找所有子机构
            String orgIds = orgInfoDao.findOrgAllChildIsList(entity);
            if (orgInfoDao.isUserOrgExist(orgIds) > 0) {
                throw new RuntimeException("机构被引用无法直接删除!");
            } else {
                orgInfoDao.deleteAllChildIs(orgIds);
            }
        } catch (Exception e) {
            log.error("逻辑删除异常!", e);
            throw new ServiceException(SysErrorCode.defaultError,e.getMessage());
        }
        return result;
    }

    @Override
    public PageInfo findDataIsPage(OrgInfoDto dto) throws Exception {
       PageInfo pageInfo=null;
       try {
           OrgInfo entity = copyTo(dto, OrgInfo.class);
           PageHelper.startPage(PN(dto.getPageNum()), PS(dto.getPageSize()));
           List list = orgInfoDao.findDataIsPage(entity);
           pageInfo=new PageInfo(list);
           pageInfo.setList(copyTo(pageInfo.getList(), OrgInfoDto.class));
       } catch (Exception e) {
           log.error("信息[分页]查询异常!", e);
           throw new ServiceException(SysErrorCode.defaultError,e.getMessage());
       }
       return pageInfo;
    }

    @Override
    public List<OrgInfoDto> findDataIsList(OrgInfoDto dto) throws Exception {
        List<OrgInfoDto>  results = null;
        try {
            OrgInfo entity = copyTo(dto, OrgInfo.class);
             results = copyTo(orgInfoDao.findDataIsList(entity), OrgInfoDto.class);
        } catch (Exception e) {
            log.error("信息[列表]查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError,e.getMessage());
        }
        return  results;
    }

    @Override
    public OrgInfoDto findDataById(OrgInfoDto dto) throws Exception {
        OrgInfoDto result = null;
        try {
            OrgInfo entity = copyTo(dto, OrgInfo.class);
            result = copyTo(orgInfoDao.selectByPrimaryKey(entity),OrgInfoDto.class);
        } catch (Exception e) {
            log.error("信息[详情]查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError,e.getMessage());
        }
        return result;
    }


    @Override
    public List<OrgInfoDto> findDataIsTree(OrgInfoDto dto) {
        try {
            List<OrgInfoDto> results = findDataIsList(dto);
            if (results == null) {
                return null;
            }
            NodeTree<OrgInfoDto> tree = new NodeTree(results, "id", "parentId", "children");
            return tree.buildTree();
        } catch (Exception e) {
            log.error("信息树获取失败!", e);
            throw new ServiceException(SysErrorCode.defaultError, e);
        }
    }

}
